package com.competition.commgr.service.impl;

import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.competition.commgr.mapper.AwardMapper;
import com.competition.commgr.domain.Award;
import com.competition.commgr.service.IAwardService;
import com.competition.common.exception.ServiceException;
import com.competition.common.utils.StringUtils;
import com.competition.common.utils.file.FileUploadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 获奖记录Service业务层处理
 */
@Service
public class AwardServiceImpl implements IAwardService
{
    @Autowired
    private AwardMapper awardMapper;

    private static final Logger logger = LoggerFactory.getLogger(AwardServiceImpl.class);

    // 定义有效的获奖等级
    private static final List<String> VALID_AWARD_LEVELS = Arrays.asList("特等奖", "一等奖", "二等奖", "三等奖", "优胜奖");

    /**
     * 查询获奖记录
     *
     * @param awardId 获奖记录主键
     * @return 获奖记录
     */
    @Override
    public Award selectAwardByAwardId(Long awardId)
    {
        return awardMapper.selectAwardByAwardId(awardId);
    }

    /**
     * 查询获奖记录列表
     *
     * @param award 获奖记录
     * @return 获奖记录
     */
    @Override
    public List<Award> selectAwardList(Award award)
    {
        return awardMapper.selectAwardList(award);
    }

    /**
     * 新增获奖记录
     *
     * @param award 获奖记录
     * @return 结果
     */
    @Override
    public int insertAward(Award award)
    {
        // 验证获奖等级
        validateAwardLevel(award.getLevel());
        return awardMapper.insertAward(award);
    }

    /**
     * 修改获奖记录
     *
     * @param award 获奖记录
     * @return 结果
     */
    @Override
    public int updateAward(Award award)
    {
        // 验证获奖等级
        validateAwardLevel(award.getLevel());
        return awardMapper.updateAward(award);
    }

    /**
     * 批量删除获奖记录
     *
     * @param awardIds 需要删除的获奖记录主键
     * @return 结果
     */
    @Override
    public int deleteAwardByAwardIds(Long[] awardIds)
    {
        return awardMapper.deleteAwardByAwardIds(awardIds);
    }

    /**
     * 删除获奖记录信息
     *
     * @param awardId 获奖记录主键
     * @return 结果
     */
    @Override
    public int deleteAwardByAwardId(Long awardId)
    {
        return awardMapper.deleteAwardByAwardId(awardId);
    }

    /**
     * 获取已审核的培训中心报名数
     * @param teamId 团队ID
     * @return 返回数
     */
    @Override
    public int getApprovedTrainingCenterRegistrations(Long teamId) {
        return awardMapper.getApprovedTrainingCenterRegistrations(teamId);
    }

    // ============== 现有方法实现 ==============

    /**
     * 检查团队成员身份
     *
     * @param userId 用户ID
     * @param teamId 团队ID
     * @return 是否是团队成员
     */
    @Override
    public boolean checkTeamMembership(Long userId, Long teamId) {
        Integer count = awardMapper.checkTeamMembership(userId, teamId);
        logger.info("团队成员检查 - 用户: {}, 团队: {}, 查询结果: {}", userId, teamId, count);
        return count != null && count > 0;
    }

    /**
     * 获取用户有权限的团队列表
     *
     * @param userId 用户ID
     * @return 团队列表
     */
    @Override
    public List<Award> selectUserTeams(Long userId) {
        return awardMapper.selectUserTeams(userId);
    }

    /**
     * 根据团队ID获取关联的赛事信息
     *
     * @param teamId 团队ID
     * @return 获奖记录（包含赛事信息）
     */
    @Override
    public Award selectCompetitionInfoByTeamId(Long teamId) {
        return awardMapper.selectCompetitionInfoByTeamId(teamId);
    }

    /**
     * 调试用户团队数据
     */
    @Override
    public List<?> debugUserTeamsDetail(Long userId) {
        return awardMapper.debugUserTeamsDetail(userId);
    }

    // ============== 新增获奖上报相关方法实现 ==============

    /**
     * 验证获奖等级
     */
    private void validateAwardLevel(String level) {
        if (StringUtils.isEmpty(level)) {
            throw new ServiceException("获奖等级不能为空");
        }
        if (!VALID_AWARD_LEVELS.contains(level)) {
            throw new ServiceException("无效的获奖等级，请选择：特等奖、一等奖、二等奖、三等奖、优胜奖");
        }
    }

    /**
     * 上报获奖记录（带文件上传）
     */
    @Override
    public int reportAward(Long sessionId, Long teamId, String level, MultipartFile certificateFile, String operName) {
        // 验证获奖等级
        validateAwardLevel(level);

        // 检查是否已存在该团队的获奖记录
        Award existingAward = awardMapper.selectAwardByTeamId(teamId);
        if (existingAward != null) {
            throw new ServiceException("该团队已有获奖记录，请使用修改功能");
        }

        Award award = new Award();
        award.setSessionId(sessionId);
        award.setTeamId(teamId);
        award.setLevel(level);
        award.setCreateBy(operName);

        // 处理文件上传
        if (certificateFile != null && !certificateFile.isEmpty()) {
            try {
                // 上传文件并获取文件路径
                String filePath = FileUploadUtils.upload(certificateFile);
                award.setCertificate(filePath);
                logger.info("获奖证书上传成功，文件路径: {}", filePath);
            } catch (IOException e) {
                logger.error("获奖证书上传失败", e);
                throw new ServiceException("证书文件上传失败");
            }
        } else {
            throw new ServiceException("请上传获奖证书");
        }

        return awardMapper.insertAward(award);
    }

    /**
     * 修改获奖记录（带文件上传）
     */
    @Override
    public int updateAwardWithFile(Long awardId, Long sessionId, Long teamId, String level, MultipartFile certificateFile, String operName) {
        // 验证获奖等级
        validateAwardLevel(level);

        Award award = new Award();
        award.setAwardId(awardId);
        award.setSessionId(sessionId);
        award.setTeamId(teamId);
        award.setLevel(level);
        award.setUpdateBy(operName);

        // 处理文件上传（如果有新文件）
        if (certificateFile != null && !certificateFile.isEmpty()) {
            try {
                // 上传文件并获取文件路径
                String filePath = FileUploadUtils.upload(certificateFile);
                award.setCertificate(filePath);
                logger.info("获奖证书更新成功，文件路径: {}", filePath);
            } catch (IOException e) {
                logger.error("获奖证书更新失败", e);
                throw new ServiceException("证书文件更新失败");
            }
        }

        return awardMapper.updateAward(award);
    }

    /**
     * 检查用户是否有权限上报该团队获奖
     */
    @Override
    public boolean checkAwardPermission(Long userId, Long teamId) {
        try {
            // 1. 检查是否是团队成员
            boolean isTeamMember = checkTeamMembership(userId, teamId);
            if (!isTeamMember) {
                logger.warn("用户 {} 不是团队 {} 的成员", userId, teamId);
                return false;
            }

            // 2. 检查团队是否通过审核
            Integer approvedCount = awardMapper.getApprovedTrainingCenterRegistrations(teamId);
            boolean isApproved = approvedCount != null && approvedCount > 0;

            if (!isApproved) {
                logger.warn("团队 {} 未通过实训中心审核", teamId);
                return false;
            }

            logger.info("用户 {} 有权限上报团队 {} 的获奖", userId, teamId);
            return true;

        } catch (Exception e) {
            logger.error("检查获奖权限时发生错误", e);
            return false;
        }
    }

    /**
     * 获取用户的所有团队（包括调试信息）
     */
    @Override
    public List<Map<String, Object>> getAllUserTeams(Long userId) {
        return awardMapper.getAllUserTeams(userId);
    }

    /**
     * 获取有效的用户团队（通过审核的团队）
     */
    @Override
    public List<Map<String, Object>> getValidUserTeams(Long userId) {
        return awardMapper.getValidUserTeams(userId);
    }
}